package com.demo.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class ConfigReader {
	
	public static final String CONFIG_PATH = System.getProperty("user.home") + "/" + "user_config.ini";

	public static HashMap<String, String> getConfig() {
		try {
			File file = new File(CONFIG_PATH);
			if (!file.exists()) {
				file.createNewFile();
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
			String line;
			HashMap<String, String> map = new HashMap<>();
			while ((line = reader.readLine()) != null) {
				if (line.startsWith("#")) {
					continue;
				}
				String[] temp = line.split("=");
				if (temp == null || temp.length != 2) {
					continue;
				}
				map.put(temp[0], temp[1]);
			}
			reader.close();
			return map;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void saveConfig(HashMap<String, String> config) {
		try {
			File file = new File(CONFIG_PATH);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			for (String key : config.keySet()) {
				fileOutputStream.write(key.getBytes("GBK"));
				fileOutputStream.write("=".getBytes("GBK"));
				fileOutputStream.write(config.get(key).getBytes("GBK"));
				fileOutputStream.write("\r\n".getBytes("GBK"));
			}
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
